package com.zwh.tool.demo;


import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.poifs.crypt.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import java.io.FileOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;

public class ExcelEncryptionExample {
    public static void main(String[] args) {
        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();

        // 创建工作表
        Sheet sheet = workbook.createSheet("Sheet1");

        // 创建行和单元格，并填充数据
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue("Hello");
        row.createCell(1).setCellValue("World");

        // 指定生成的Excel文件路径
        String excelFilePath = "D:\\idea\\file\\file.xlsx";

        try {
            // 保存Excel文件
            FileOutputStream fileOut = new FileOutputStream(excelFilePath);
            workbook.write(fileOut);
            fileOut.close();

            // 加密Excel文件
            encryptExcelFile(excelFilePath, "yourPassword");

            System.out.println("Excel file created and encrypted successfully!");

        } catch (IOException | GeneralSecurityException e) {
            e.printStackTrace();
        }
    }

    private static void encryptExcelFile(String filePath, String password)
            throws IOException, GeneralSecurityException {
        // 读取Excel文件
        POIFSFileSystem fs = new POIFSFileSystem();
        EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);

        Encryptor enc = info.getEncryptor();
        enc.confirmPassword(password);

        // 使用加密信息包装文件系统
//        try (FileOutputStream fos = new FileOutputStream(filePath);
//             EncryptionOutputStream encos = enc.getDataStream(fs, fos)) {
//            fs.writeFilesystem(encos);
//        }
    }
}
